#ifndef ASYNCWEBSYNCHRONIZATION_H_
#define ASYNCWEBSYNCHRONIZATION_H_

#include "ESPAsyncWebServer.h"

class AsyncWebLock {
private:
    SemaphoreHandle_t       m_lock;         // 二进制信号量
    mutable TaskHandle_t    m_lockedBy;     // 持有锁的线程

public:
    AsyncWebLock()
    {
        m_lock = xSemaphoreCreateBinary();
        m_lockedBy = nullptr;
        xSemaphoreGive(m_lock);
    }
    ~AsyncWebLock()
    {
        vSemaphoreDelete(m_lock);
    }

    bool lock() const
    {
        auto current_task = xTaskGetCurrentTaskHandle();
        if (m_lockedBy != current_task) {
            xSemaphoreTake(m_lock, portMAX_DELAY);
            m_lockedBy = current_task;
            return true;
        }
        return false;
    }

    void unlock() const
    {
        m_lockedBy = nullptr;
        xSemaphoreGive(m_lock);
    }
};

// 用于自动管理锁的获取和释放
class AsyncWebLockGuard {
private:
    const AsyncWebLock* m_lock;
public:
    AsyncWebLockGuard(const AsyncWebLock &l)
    {
        m_lock = l.lock() ? &l : nullptr;
    }
    ~AsyncWebLockGuard()
    {
        if (m_lock != nullptr) {
            m_lock->unlock();
        }
    }
};

#endif